//! 上下文管理器 (ContextManager)
//!
//! 对应 `ai-server` 的 `services/context_manager.py`。
//! 职责：
//! - 创建和缓存每个插件的 `ActivateContext`。
//! - 在创建上下文时，执行依赖注入，将依赖的服务注入到上下文中。
//! - 创建和缓存 `RequestContributionContext`。

use std::any::Any;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use crate::core::beans::bean::{Bean, BeanManager, IDestructible};
use crate::core::beans::constants::expansion_feature_names;
use crate::core::services::context::{ActivateContext, RequestContributionContext};
use crate::core::services::contribution_keyword_manager::ContributionKeywordManager;
use crate::core::services::event_manager::EventManager;
use crate::core::services::extension_manager::ExtensionManager;
use crate::core::services::manifest_manager::ManifestManager;
use crate::core::services::protocols::IRequestContributionContext;

/// 上下文管理器
pub struct ContextManager {
    bean_manager: Arc<BeanManager>,
    activate_context_pool: Mutex<HashMap<String, Arc<ActivateContext>>>,
    request_contribution_context_pool: Mutex<HashMap<String, Arc<dyn IRequestContributionContext + Send + Sync>>>,
}

impl IDestructible for ContextManager {
    fn destructor(&self) {
        let mut pool = self.activate_context_pool.lock().unwrap();
        for context in pool.values() {
            context.destructor();
        }
        pool.clear();
        self.request_contribution_context_pool.lock().unwrap().clear();
        println!("ContextManager destroyed.");
    }
}

impl Bean for ContextManager {
    fn new(bean_manager: &Arc<BeanManager>) -> Arc<Self> {
        Arc::new(Self {
            bean_manager: bean_manager.clone(),
            activate_context_pool: Mutex::new(HashMap::new()),
            request_contribution_context_pool: Mutex::new(HashMap::new()),
        })
    }
}

impl ContextManager {
    /// 获取或创建一个插件的激活上下文
    pub fn get_activate_context(&self, name: &str) -> Arc<ActivateContext> {
        let mut pool = self.activate_context_pool.lock().unwrap();
        if let Some(context) = pool.get(name) {
            return context.clone();
        }

        // --- 如果上下文不存在，则创建 --- 
        let manifest_manager = self.bean_manager.get_bean::<ManifestManager>(expansion_feature_names::MANIFEST_MANAGER).unwrap();
        let extension_manager = self.bean_manager.get_bean::<ExtensionManager>(expansion_feature_names::EXTENSION_MANAGER).unwrap();
        let contribution_manager = self.bean_manager.get_bean::<ContributionKeywordManager>(expansion_feature_names::CONTRIBUTION_KEYWORD_MANAGER).unwrap();
        let event_manager = self.bean_manager.get_bean::<EventManager>(expansion_feature_names::EVENT_MANAGER).unwrap();

        let manifest = manifest_manager.get_manifest(name).expect("Manifest not found during context creation");

        // 依赖注入的核心逻辑
        let mut services_for_injection = HashMap::<String, Arc<dyn Any + Send + Sync>>::new();
        if let Some(dependencies) = &manifest.dependencies {
            for dep_name in dependencies.keys() {
                if let Some(dep_manifest) = manifest_manager.get_manifest(dep_name) {
                    // 检查依赖的插件是否提供了 context
                    if dep_manifest.provide_context.unwrap_or(false) {
                        let context_name = dep_manifest.context_name.as_deref().unwrap_or(dep_name);
                        if let Some(context_instance) = extension_manager.get_context(&dep_manifest, name) {
                            services_for_injection.insert(context_name.to_string(), context_instance);
                        }
                    }

                    // 检查依赖的插件是否提供了 contribution_keywords 的 context
                    if let Some(keywords) = &dep_manifest.contribution_keywords {
                        for keyword_def in keywords {
                            if keyword_def.provide_context.unwrap_or(false) {
                                let context_name = keyword_def.context_name.as_deref().unwrap_or(&keyword_def.name);
                                if let Some(keyword_context) = contribution_manager.get_contribution_keyword_context(&keyword_def.name, name) {
                                    services_for_injection.insert(context_name.to_string(), keyword_context);
                                }
                            }
                        }
                    }
                }
            }
        }

        // 创建新的上下文
        let new_context = Arc::new(ActivateContext::new(
            manifest.clone(),
            manifest_manager,
            extension_manager,
            contribution_manager,
            event_manager,
            services_for_injection,
        ));

        pool.insert(name.to_string(), new_context.clone());
        new_context
    }

    pub fn destroy_activate_context(&self, name: &str) {
        if let Some(context) = self.activate_context_pool.lock().unwrap().remove(name) {
            context.destructor();
        }
    }

    /// 获取或创建一个请求贡献的上下文
    pub fn get_request_contribution_context(&self, name: &str, keyword: &str) -> Arc<dyn IRequestContributionContext + Send + Sync> {
        let key = format!("{}-{}", name, keyword);
        let mut pool = self.request_contribution_context_pool.lock().unwrap();
        if let Some(context) = pool.get(&key) {
            return context.clone();
        }

        let manifest_manager = self.bean_manager.get_bean::<ManifestManager>(expansion_feature_names::MANIFEST_MANAGER).unwrap();
        let manifest = manifest_manager.get_manifest(name).expect("Manifest not found");

        let new_context = Arc::new(RequestContributionContext::new(manifest));
        pool.insert(key, new_context.clone());
        new_context
    }
}